//
//  PictureViewController.m
//  ForAddSDK
//
//  Created by admin on 2018/1/9.
//  Copyright © 2018年 admin. All rights reserved.
//

#import "PictureViewController.h"
#import "DragDropImageView.h"
#import "DataHandler.h"

#define ICON_SUB_PATH @"/arpg iOS/Images.xcassets/AppIcon.appiconset"
#define FLASH_SUB_PATH @"/arpg iOS/Images.xcassets/Brand Assets.launchimage"

@interface PictureViewController ()

@property (weak) IBOutlet DragDropImageView *transparentIcon;
@property (weak) IBOutlet DragDropImageView *whiteBaseIcon;
@property (weak) IBOutlet DragDropImageView *flashPicture;
@property (weak) IBOutlet DragDropImageView *loadingPicture;
@property (weak) IBOutlet DragDropImageView *loginPicture;
@property (weak) IBOutlet DragDropImageView *logoPicture;
@property (unsafe_unretained) IBOutlet NSTextView *logTextView;

@end

@implementation PictureViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do view setup here.
}

#pragma mark -ICON处理

- (IBAction)outPutIcon:(id)sender {
    NSLog(@"transparentIcon path = %@", _transparentIcon.path);
    NSLog(@"whiteBaseIcon path = %@", _whiteBaseIcon.path);
    if (_transparentIcon.path.length == 0 || _whiteBaseIcon.path.length == 0) {
        _logTextView.string = @"请放置透明底ICON和白底ICON";
    }
    else {
        DataHandler *handler = [DataHandler shareInstance];
        if (!handler.isPathOK || handler.workPlatform.length == 0 || handler.projectSubPath.length == 0) {
            _logTextView.string = @"请回到路径相关页面设置有效路径和平台名";
        }
        else if (![DataHandler isExistPlatformProject:handler.workPlatform]) {
            _logTextView.string = [NSString stringWithFormat:@"%@工程不存在",handler.workPlatform];
            return ;
        }
        //icon处理
        NSImage *transparentImage = [[NSImage alloc] initWithContentsOfFile:_transparentIcon.path];
        NSString *iconPath = [NSString stringWithFormat:@"%@%@/proj.ios_appstore_%@%@",handler.svnPath,handler.projectSubPath,handler.workPlatform,ICON_SUB_PATH];
        NSString *logTransparentIcon = [DataHandler runScript:@"removeSpecifiSuffixFile" type:@"sh" launchPath:@"/bin/bash" arguments:@[iconPath,@"png"]];
        [self saveImage:transparentImage atPath:iconPath];
        //白底icon处理
        
        NSString *logWhiteBaseIcon = [DataHandler runScript:@"copyFile" type:@"sh" launchPath:@"/bin/bash" arguments:@[_whiteBaseIcon.path,[NSString stringWithFormat:@"%@/Icon-1024.png",iconPath]]];
        _logTextView.string = [NSString stringWithFormat:@"%@%@\nICON保存已保存到路径%@",logTransparentIcon,logWhiteBaseIcon,iconPath];
    }
}

- (void)saveImage:(NSImage *)image atPath:(NSString *)path {
    
    //大小
    NSArray * sizeArr = @[@"20.0",@"40.0",@"40.0",@"60.0",@"29.0",@"58.0",@"87.0",@"80.0",@"120.0",@"57.0",@"114.0",@"120.0",@"180.0",@"29.0",@"58.0",@"40.0",@"80.0",@"50.0",@"100.0",@"72.0",@"144.0",@"76.0",@"152.0",@"167.0"];
    
    //名称
    NSArray * nameArr = @[@"Icon-iPad-20",@"Icon-iPad-20@2x",@"Icon-iPhone-20@2x",@"Icon-iPhone-20@3x",@"Icon-iPhone-29",@"Icon-iPhone-29@2x",@"Icon-iPhone-29@3x",@"Icon-iPhone-40@2x",@"Icon-iPhone-40@3x",@"Icon-iPhone-57",@"Icon-iPhone-57@2x",@"Icon-iPhone-60@2x",@"Icon-iPhone-60@3x",@"Icon-iPad-29",@"Icon-iPad-29@2x",@"Icon-iPad-40",@"Icon-iPad-40@2x",@"Icon-iPad-50",@"Icon-iPad-50@2x",@"Icon-iPad-72",@"Icon-iPad-72@2x",@"Icon-iPad-76",@"Icon-iPad-76@2x",@"Icon-iPad-83.5@2x"];
    
    for (int i = 0; i< sizeArr.count || i < nameArr.count; i++) {
        
        NSString * fullpath = [NSString stringWithFormat:@"%@/%@.png",path,nameArr[i]];
        
        NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithCGImage:[self createScaleImageByXY:[self createCGImageRefFromNSImage:image] Width:[sizeArr[i] floatValue] Height:[sizeArr[i] floatValue]]];
        
        NSDictionary *imageProps = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:1.0] forKey:NSImageInterlaced];
        NSData * imageData = [imageRep representationUsingType:NSPNGFileType properties:imageProps];
        [imageData writeToFile:fullpath atomically:NO];
        
        NSLog(@"导出图片%f:%f",imageRep.size.width,imageRep.size.height);
    }
}

-(CGImageRef )createCGImageRefFromNSImage:(NSImage* )image
{
    NSData *imageData;
    CGImageRef imageRef;
    @try {
        imageData = [image TIFFRepresentation];
        if (imageData) {
            CGImageSourceRef imageSource = CGImageSourceCreateWithData((CFDataRef)imageData, NULL);
            NSDictionary* options = [NSDictionary dictionaryWithObjectsAndKeys:
                                     (id)kCFBooleanFalse, (id)kCGImageSourceShouldCache,
                                     (id)kCFBooleanTrue, (id)kCGImageSourceShouldAllowFloat,
                                     nil];
            
            //要用这个带option的 kCGImageSourceShouldCache指出不需要系统做cache操作 默认是会做的
            imageRef = CGImageSourceCreateImageAtIndex(imageSource, 0, (CFDictionaryRef)options);
            CFRelease(imageSource);
            return imageRef;
        }else{
            return NULL;
        }
    }
    @catch (NSException *exception) {
        
    }
    @finally {
        
    }
    
    return NULL;
}

- (CGImageRef )createScaleImageByXY:(CGImageRef )image Width :(float )width Height :(float )height
{
    CGContextRef content = [self MyCreateBitmapContextWidth:width Height:height];
    CGContextDrawImage(content, CGRectMake(0, 0, width, height), image);
    CGImageRef img = CGBitmapContextCreateImage(content);
    return img;
}

- (CGContextRef ) MyCreateBitmapContextWidth : (int )pixelsWide
                                      Height :(int) pixelsHigh
{
    CGContextRef context = NULL;
    CGColorSpaceRef colorSpace;
    GLubyte*bitmapData;
    int bitmapByteCount;
    int bitmapBytesPerRow;
    bitmapBytesPerRow = (pixelsWide * 4);
    bitmapByteCount = (bitmapBytesPerRow * pixelsHigh);
    colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB);//CGColorSpaceCreateDeviceRGB();//
    bitmapData = (GLubyte*)calloc(bitmapByteCount,sizeof(GLubyte));//or malloc(bitmapByteCount);//
    
    if (bitmapData == NULL) {
        fprintf(stderr, "Memory not allocated!");
        return NULL;
    }
    
    context = CGBitmapContextCreate(bitmapData,
                                    pixelsWide,
                                    pixelsHigh,
                                    8,
                                    bitmapBytesPerRow,
                                    colorSpace,
                                    kCGImageAlphaPremultipliedLast);
    if (context == NULL) {
        free(bitmapData);
        fprintf(stderr, "Context not created!");
        return NULL;
    }
    CGColorSpaceRelease(colorSpace);
    return context;
}

#pragma mark -闪屏图片处理

- (IBAction)outPutFlashPicture:(id)sender {
    NSLog(@"flashPicture path = %@", _flashPicture.path);
    DataHandler *handler = [DataHandler shareInstance];
    if (_flashPicture.path.length == 0) {
        _logTextView.string = @"请放置闪屏图";
    }
    else if (!handler.isPathOK || handler.workPlatform.length == 0 || handler.projectSubPath.length == 0) {
        _logTextView.string = @"请回到路径相关页面设置有效路径和平台名";
    }
    else if (![DataHandler isExistPlatformProject:handler.workPlatform]) {
        _logTextView.string = [NSString stringWithFormat:@"%@工程不存在",handler.workPlatform];
    }
    else {
        NSString *flashPath = [NSString stringWithFormat:@"%@%@/proj.ios_appstore_%@%@",handler.svnPath,handler.projectSubPath,handler.workPlatform,FLASH_SUB_PATH];
        _logTextView.string = [DataHandler runScript:@"removeSpecifiSuffixFile" type:@"sh" launchPath:@"/bin/bash" arguments:@[flashPath,@"png"]];
        NSImage *flashImage = [[NSImage alloc] initWithContentsOfFile:_flashPicture.path];
        [self processSplashScreen:flashImage atPath:flashPath];
        _logTextView.string = [NSString stringWithFormat:@"闪屏图保存已到路径%@",flashPath];
    }
}

- (void)processSplashScreen:(NSImage *)image atPath:(NSString *)path {
    NSImage *horizontal = nil;
    NSImage *vertical = nil;
    if (image.size.width > image.size.height) {
        horizontal = image;
        vertical = [self rotateImage:image byDegrees:270];
    }
    else {
        vertical = image;
        horizontal = [self rotateImage:image byDegrees:90];
    }
    
    //
    NSArray * widthArr = @[@"640.0",@"750.0",@"1242.0",@"2048.0",@"1024.0",@"1536.0",@"768.0",@"320.0",@"640.0",@"1125.0"];
    //
    NSArray * heightArr = @[@"1136.0",@"1334.0",@"2208.0",@"1536.0",@"768.0",@"2048.0",@"1024.0",@"480.0",@"960.0",@"2436.0"];
    
    //名称
    NSArray * nameArr = @[@"Default-568h@2x",@"Default-ip6",@"Default-ip6p",@"Default-Landscape@2x~ipad",@"Default-Landscape~ipad",@"Default-Portrait@2x~ipad",@"Default-Portrait~ipad",@"Default",@"Default@2x",@"Default-iOS11-812h@3x"];
    
    
    for (int i = 0; i< widthArr.count; i++) {
        NSImage *useImage = horizontal;
        if ([heightArr[i] floatValue] - [widthArr[i] floatValue] > 0.000001) {
            useImage = vertical;
        }
        
        NSString * fullpath = [NSString stringWithFormat:@"%@/%@.png",path,nameArr[i]];
        NSLog(@"path -- %@", path);
        NSLog(@"fullpath -- %@", fullpath);
        
        NSBitmapImageRep *imageRep = [[NSBitmapImageRep alloc] initWithCGImage:[self createScaleImageByXY:[self createCGImageRefFromNSImage:useImage] Width:[widthArr[i] floatValue] Height:[heightArr[i] floatValue]]];
        
        NSDictionary *imageProps = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:1.0] forKey:NSImageInterlaced];
        NSData * imageData = [imageRep representationUsingType:NSPNGFileType properties:imageProps];
        [imageData writeToFile:fullpath atomically:NO];
        
        NSLog(@"导出闪屏图片%f:%f",imageRep.size.width,imageRep.size.height);
    }
}

//按照图片的中心旋转90.180.270,360度
- (NSImage *) rotateImage:(NSImage*)sourceImage byDegrees:(float)deg
{
    NSSize srcsize= [sourceImage size];
    float srcw = srcsize.width;
    float srch= srcsize.height;
    float newdeg = 0;
    //旋转弧度
    //double ratain = ((deg/180) * PI);
    NSRect r1;
    if(0< deg && deg <=90)
    {
        r1 = NSMakeRect(0.5*(srcw -srch), 0.5*(srch-srcw), srch, srcw);
        newdeg = 90.0;
    }
    if(90< deg && deg <=180)
    {
        r1 = NSMakeRect(0, 0, srcw, srch);
        newdeg = 180.0;
    }
    if(180< deg && deg <=270)
    {
        r1 = NSMakeRect(0.5*(srcw -srch), 0.5*(srch-srcw), srch, srcw);
        newdeg = 270.0;
    }
    if(270< deg && deg <=360)
    {
        r1 = NSMakeRect(0, 0, srch, srcw);
        newdeg = 360;
    }
    
    //draw new image
    NSImage *rotated = [[NSImage alloc] initWithSize:[sourceImage size]];
    [rotated lockFocus];
    NSAffineTransform *transform = [NSAffineTransform transform];
    [transform translateXBy:(0.5*srcw) yBy: (0.5*srch)];  //按中心图片旋转
    [transform rotateByDegrees:newdeg];                   //旋转度数，rotateByRadians：使用弧度
    [transform translateXBy:(-0.5*srcw) yBy: (-0.5*srch)];
    [transform concat];
    [[sourceImage bestRepresentationForDevice: nil] drawInRect: r1];//矩形内画图
    
    //[sourceImage drawInRect:r1 fromRect:NSZeroRect operation:NSCompositeCopy fraction:1.0];
    //[sourceImage drawAtPoint:arge/*NSZeroPoint*/ fromRect:NSMakeRect(arge.x, arge.y,ww ,wh)/*NSZeroRect*/ operation:NSCompositeCopy fraction:1.0];
    [rotated unlockFocus];
    
    return rotated;
}

#pragma mark -图片资源处理 加载图、登陆图、logo
- (IBAction)outPutOtherPicture:(id)sender {
    NSLog(@"loadingPicture path = %@", _loadingPicture.path);
    NSLog(@"loginPicture path = %@", _loginPicture.path);
    NSLog(@"logoPicture path = %@", _logoPicture.path);
    DataHandler *handler = [DataHandler shareInstance];
    if (!handler.isPathOK || handler.workPlatform.length == 0 || handler.pictureSubPath.length == 0) {
        _logTextView.string = @"请回到路径相关页面设置有效路径和平台名";
    }
    else if (![DataHandler isexistPictureFolder:handler.workPlatform]) {
        _logTextView.string = [NSString stringWithFormat:@"%@图片资源不存在",handler.workPlatform];
    }
    else if (_loadingPicture.path.length != 0 || _loginPicture.path.length != 0 || _logoPicture.path.length != 0) {
        NSString *otherPicturePath = [NSString stringWithFormat:@"%@%@/%@",handler.svnPath,handler.pictureSubPath,handler.workPlatform];
        NSMutableArray *paths = [NSMutableArray arrayWithObject:otherPicturePath];
        _loadingPicture.path.length ? [paths addObject:_loadingPicture.path] : [paths addObject:@""];
        _loginPicture.path.length ? [paths addObject:_loginPicture.path] : [paths addObject:@""];
        _logoPicture.path.length ? [paths addObject:_logoPicture.path] : [paths addObject:@""];
        _logTextView.string = [DataHandler runScript:@"changePictures" type:@"sh" launchPath:@"/bin/bash" arguments:paths];
    }
    else {
        _logTextView.string = @"请放置图片资源";
    }
}

@end
